<template>
  <div id="editCollectionFile">
    <el-form :model="formData" label-width="40%" style="width:80%">
      <el-form-item label="文件类型" prop="brandId">
        <el-select v-model="formData.type" placeholder="请选择" style="width:80%">
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上传文件">
        <upload-file
          :limit="1"
          :path-prefix="pathPrefix"
          :upload-list="uploadList"
          @upload-file="uploadFileRes"
        />
      </el-form-item>
      <el-form-item style="margin-top:30px">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'EditCollectionFile',
}
</script>

<script setup>

import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { addCollectionFile, updateCollectionFile } from '@/api/collection'
import UploadFile from '@/components/upload/uploadFile.vue'
import { detail } from '@/api/api'

const props = defineProps(['detail'])
const emit = defineEmits(['editRes'])

const typeList = ref([
  {
    label: '主文件',
    value: 10,
  },
  {
    label: '子文件',
    value: 20,
  },
  {
    label: '封面图',
    value: 30,
  },
])

const pathPrefix = ref('w3/yjc3/collection/model')

const formData = ref({})

const uploadList = ref([])

const uploadFileRes = (fileList) => {
  formData.value.fileUrl = fileList[0].name
}

const onCancel = () => {
  editRes()
}

const onSubmit = async() => {
  if (formData.value.id === undefined) {
    formData.value.collectionId = props.detail.collectionId
    // 添加
    const res = await addCollectionFile(formData.value)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '添加成功！'
      })
      editRes()
    }
  } else {
    // 更新
    const res = await updateCollectionFile(formData.value)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '更新成功！'
      })
      editRes()
    }
  }
}

const editRes = () => {
  emit('editRes', false)
}

const initDetail = () => {
  formData.value = props.detail

  if (props.detail.fileUrl !== undefined) {
    uploadList.value.push({
      fileUrl: props.detail.fileUrl,
      name: props.detail.filename,
    })
    formData.value.fileUrl = props.detail.filename
  }
}

initDetail()

</script>
